package org.idea.qiyu.framework.nacos.starter.controller;

import com.alibaba.nacos.api.exception.NacosException;
import org.idea.qiyu.framework.nacos.starter.bean.ModifyNacosPropertiesBean;
import org.idea.qiyu.framework.nacos.starter.client.INacosClientService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author linhao
 * @Date created in 5:16 下午 2021/10/4
 */
@RestController
@RequestMapping(value = "/nacos")
public class NacosController {

    @Resource
    private INacosClientService iNacosClientService;

    @GetMapping(value = "/get-all-config")
    public Map<String, String> getAllConfig() throws NacosException {
        Map<String, String> resultMap = iNacosClientService.getAllProperty("qiyu-common.properties", "test-env", "DEFAULT_GROUP");
        return resultMap;
    }

    @PostMapping(value = "/add-properties")
    public boolean addProperties(String key, String value) throws NacosException {
        ModifyNacosPropertiesBean modifyNacosPropertiesBean = new ModifyNacosPropertiesBean();
        modifyNacosPropertiesBean.setDataId("qiyu-common.properties");
        modifyNacosPropertiesBean.setGroupId("DEFAULT_GROUP");
        modifyNacosPropertiesBean.setNamespace("test-env");
        Map<String, Object> propertiesMap = new HashMap<>();
        propertiesMap.put(key, value);
        modifyNacosPropertiesBean.setPropertiesMap(propertiesMap);
        return iNacosClientService.addProperties(modifyNacosPropertiesBean);
    }

    @PostMapping(value = "/remove-properties")
    public boolean removeProperties(String key) throws NacosException {
        ModifyNacosPropertiesBean modifyNacosPropertiesBean = new ModifyNacosPropertiesBean();
        modifyNacosPropertiesBean.setDataId("qiyu-common.properties");
        modifyNacosPropertiesBean.setGroupId("DEFAULT_GROUP");
        modifyNacosPropertiesBean.setNamespace("test-env");
        modifyNacosPropertiesBean.setRemoveKeys(Arrays.asList(key));
        return iNacosClientService.removeProperties(modifyNacosPropertiesBean);
    }

    @PostMapping(value = "/remove-hold-properties")
    public boolean removeHoldProperties() throws NacosException {
        ModifyNacosPropertiesBean modifyNacosPropertiesBean = new ModifyNacosPropertiesBean();
        modifyNacosPropertiesBean.setDataId("qiyu-common.properties");
        modifyNacosPropertiesBean.setGroupId("DEFAULT_GROUP");
        modifyNacosPropertiesBean.setNamespace("test-env");
        return iNacosClientService.removeHoldConfig(
                modifyNacosPropertiesBean.getDataId(),
                modifyNacosPropertiesBean.getGroupId(),
                modifyNacosPropertiesBean.getNamespace());
    }

}
